<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Controllers\MainController;
use DB;
class BrandController extends Controller
{
	public static $path = './uploads/images/brandpic';
    /**
    *品牌添加页面
    */
    public function getAdd()
    {
        return view('/admin/brand/add');
    }
    /**
	*执行品牌添加
    */
    public function postInsert(Request $request)
    {
    	$arr = $request ->except('_token');
    	if($request ->hasFile('brandpic'))
    		$arr = MainController::uploadPic('brandpic', $request, $arr, $path = self::$path);
    	//dd($arr);
    	$res = DB :: table('shop_brand') ->insert($arr);
    	if($res){
            return redirect('/admin/brand/index') -> with('success', '品牌添加成功');
        }else{
            return back() -> withInput() -> with('error', '品牌添加失败');
        }	
    }
    /**
	*品牌显示页面
    */
    public function getIndex(Request $request)
    {
    	$count = $request -> input('count',10);
        $search = $request -> input('search','');
        //带条件查询数据，并且分页
        $data = DB::table('shop_brand')->where('brandname','like','%'.$search.'%')->paginate($count);
        $page = $request -> input('page',1);
        $start = ($page - 1) * $count + 1;
        $sum = count(DB :: table('shop_brand') -> where('brandname','like','%'.$search.'%') ->get()); 
        $end = min($page * $count,$sum);
        return view('/admin/brand/index',['data'=>$data,'request' =>$request -> all(), 'start' => $start, 'end' => $end, 'sum' => $sum, 'page' =>$page]);
    }
    /**
	*执行品牌修改页面
    */
    public function getEdit($page = 1, $id)
    {
    	$data = DB :: table('shop_brand') ->where('id', $id) ->first();
    	return view('/admin/brand/edit', ['data' =>$data, 'page' =>$page]);
    }
    /**
	*执行品牌修改，修改后回到当前页
    */
    public function postUpdate(Request $request)
    {
    	$arr = $request ->except(['_token', 'id', 'brandpic' ,'page']);
    	$page = $request ->input('page');
    	$id = $request ->input('id');
    	if($request ->hasFile('brandpic'))
    		$arr = MainController::uploadPic('brandpic', $request, $arr, $path = self::$path);
    	//dd($arr);
    	$res = DB :: table('shop_brand') ->where('id', $id) ->update($arr);
    	if($res){
            return redirect('/admin/brand/index?page='.$page) -> with('success', '品牌修改成功');
        }else{
            return back() -> withInput() -> with('error', '品牌修改失败');
        }	
    }
    /**
	*执行品牌删除
    */
    public function getDelete($id)
    {
    	$res = DB :: table('shop_brand') ->where('id', $id) ->delete();
    	if($res){
            return redirect('/admin/brand/index') -> with('success', '品牌删除成功');
        }else{
            return back() -> withInput() -> with('error', '品牌删除失败');
        }
    }
}
